<?php

require_once 'core.php';
require_once cf\Config::path.'shop.php';

$tpl = 'import_yml';

$step = 1;
$smarty->assignByRef('step', $step);

function do_edit_save($aid, $params) {
	global $step, $smarty, $view;

	if (array_key_exists('yml_id',$params)) {
		$step=3;
		$ymlID = $params['yml_id'];
		$path = $params['file_path'];
		$smarty->assign('ymlID', $ymlID);
		exec('php '.cf\Config::path."cron/shop/import/yml.php $ymlID $path &");
	} else {
		$step=2;
		$path = sys_get_temp_dir().uniqid('yml');
		if (array_key_exists('url',$_FILES)) {
			if ($_FILES['url']['type']=='url') {
				$params['url'] = $_FILES['url']['name'];
				if (!copy($_FILES['url']['name'],$path)) {
					die("Can't copy file from URL:".$_FILES['url']['name']);
				}
			} elseif ($_FILES['url']['type']) {
				if (UPLOAD_ERR_OK != $_FILES['url']['error'] || !is_uploaded_file($_FILES['url']['tmp_name'])) {
					die("The file could't be uploaded [".$_FILES['url']['error']."], check 'upload_max_filesize' or 'post_max_size' in php.ini");
				}
				if (!move_uploaded_file($_FILES['url']['tmp_name'], $path)) {
					die("Can't move uploaded file");
				}			
			} else {
				if (!copy($params['url'],$path)) {
					die("Can't copy file from URL:".$params['url']);
				}
			}
			unset($_FILES['url']);
		}
		
		$id = cf\api\admin\doAction(cf\param::get('aid'),$params);
		$assigned = array();
		if (array_key_exists('id',$params)) {
			$id = $params['id'];
			$importCat = cf\query2arrays("SELECT from_id,to_id FROM cf_import_yml_categories WHERE yml_id=:id",array('id'=>$id));
			foreach ($importCat as $fromTo) {
				$assigned[$fromTo['from_id']] = $fromTo['to_id'];
			}
		}
		$smarty->assign('ymlID', $id);
		$smarty->assign('assigned',json_encode($assigned));
		$smarty->assign('file_path',$path);
				
		global $categories;
		loadCategoriesFromYML($path);
		$smarty->assign('allCategories',json_encode(createCategoriesTree()));
	}
}

$categories = array();
$catID = 0;
$stopParse = false;
	
function loadCategoriesFromYML($path) {
	function onStartTag($parser, $name, $attrs) {
		global $categories, $catID;
		if ($name=='CATEGORY') {
			$catID = $attrs['ID'];
			$categories[$catID] = array(
				'ID' => $attrs['ID'],
				'parentID' => array_key_exists('PARENTID',$attrs) ? $attrs['PARENTID'] : null,
				'name' => ''
			);
		}
	}
	function onEndTag($parser,$name) {
		global $catID, $stopParse;
		if ($name == 'CATEGORY') {
			$catID = 0;
		}
		if ($name == 'CATEGORIES') {
			$stopParse = true;
		}
	}
	function onText($parser, $data) {
		global $categories, $catID;
		if ($catID) {
			$categories[$catID]['name'] .= $data;
		}
	}
	
	$f = fopen($path,'r');
	if ($f===false) {
		die("Could't open TMP file");
	}
	$parser = xml_parser_create('UTF-8');
	xml_set_element_handler($parser, 'onStartTag', 'onEndTag');
	xml_set_character_data_handler ($parser, 'onText');
	global $stopParse;
	while (($data=fread($f, 1024)) && !$stopParse) {
		if (!xml_parse($parser, $data, feof($f))) {
			die(sprintf("XML error: %s at line %d",
				xml_error_string(xml_get_error_code($parser)),
				xml_get_current_line_number($parser))
			);
		}
	}
	xml_parser_free($parser);
	fclose($f);
}

function createCategoriesTree($parentId=null, &$items=array()) {
	global $categories;
	foreach ($categories as $id => $cat) {
		if ($cat['parentID'] == $parentId) {
			$item = array(
				'' => array(
					'id'=>$cat['ID']
				)
			);
			createCategoriesTree($cat['ID'],$item);
			$items[ $cat['name'] ] = $item;
		}
	}
	return $items;
}

require_once 'edit.php';
?>